//手动引入封装的axios  network
import axios from 'axios'
//相当于index.js里面的一个小组件（模块）
const classify = {
  state: {
    subCategoryItems: [],
    selectIndex: 0,
    category: [],
    secondCategory: [],
    firstcategory: [],
    aboutCategory: []
  },
  mutations: {
    getfirst(state, item) {
      //保存数据到数组
      state.aboutCategory = [...item]
      //遍历出数组中pid=0 的数据
      state.aboutCategory.forEach(element => {
        if (element.pid == 0) {
          //pid为0的数据放在一个数组中
          state.firstcategory.push(element)
        }
      });
      //显示一级导航中下标为0的id
      var id = state.firstCategory[0].id;
      //遍历出pid=="下标为0 的id"  也就是二级导航
      state.aboutCategory.forEach(element => {
        if (element.pid == id) {
          //把二级导航放在一个数组中
          state.secondCategory.push(element)
        }
      });
    },
    getsecond(state, item) {
      state.secondCategory = []
      var id = item.id
      state.secondCategory.forEach(element => {
        if (element.pid == id) {
          state.secondCategory.push(element)
        }
      });
    },
    //state状态 categoryItems是获取到的数据 
    getclassify(state, categoryItems) {
      state.category = [...categoryItems]//把数据放到空数组
    },
    getchange(state, index) {
      //下标
      state.selectIndex = index;
      //点击一级导航显示二级导航
      state.subCategoryItems.pid = state.category[state.selectIndex].id
    },

  },
  actions: {
    getclassify(context) {
      //使用axios获取到一级导航的数据
      axios.get("https://api.it120.cc/small4/shop/goods/category/all")
        .then((res) => {
          console.log(res.data.data)
          //触发getclassify这个函数把res.data传给getclassify
          context.commit('getclassify', res.data.data)
        })
    },
    getchange(context, index) {
      //给getchange传当前下标的值
      context.commit("getchange", index)
    }
  },
  modules: {
  }
}

//抛出module
export default classify;
